﻿using System;
using System.Windows.Forms;
using PersonalAccoutingProgram.Data;
using System.Linq;

public partial class EnterIncomes : Form
{
    private string userName;

    public EnterIncomes(string currentUsername)
    { 
        InitializeComponent();
        InitializeControls(currentUsername);
    }

    private void InitializeControls(string currentUsername)
    {
        InitializeIncomes();
        this.userName = currentUsername;
        dateTimePicker.Format = DateTimePickerFormat.Custom;
        dateTimePicker.CustomFormat = DateFormat.DATE_TIME_FORMAT;
    }

    private void InitializeIncomes()
    {
        var allOrigins =
        OriginDataClassesDataContext.GetAllOrigines();
        comboCategory.Items.AddRange(allOrigins.ToArray());       
    }

    private void EnterIncomes_Load(object sender, EventArgs e)
    { 
    }

    private void btnAdd_Click(object sender, EventArgs e)
    { 
        try
        {
            if (comboCategory.SelectedIndex == -1)
            {
                throw new ArgumentException("Not selected category!");
            }
            if (tbAmount.Text == String.Empty)
            {
                throw new ArgumentException("The amount is not entered!");
            }
            if (DataValidator.isAmountValid(tbAmount.Text))
            { 
                string amountForAdd = String.Format("{0:0.00}", tbAmount.Text);
                decimal amount = decimal.Parse(amountForAdd);
                var userID =
                UserDataClassesDataContext.GetUserID(userName);
                int originID = comboCategory.SelectedIndex + 1;
                int userIntID = userID.First(id => id > 0);
                DateTime date = DateTime.Parse(dateTimePicker.Text);
                IncomeDataClassesDataContext.AddNewIncomes(
                    amount, originID, userIntID, date);
                MessageBox.Show("Added successfully!");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void tbAmount_KeyPress(object sender, KeyPressEventArgs e)
    {
        DataValidator.ValidateAmount(e);
    }
}